import {
  ProFormCheckbox,
  ProFormDigit,
  ProFormRadio,
  ProFormSwitch,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import React, { Key, useState } from 'react';
import { addItem, delItem, detailItem, getTreeList, updateItem } from '@/services/system/menu';
import { getOptionBtn } from '@/util/table';
import { AUTH_TYPE, MENU_CODES } from '@/options';
import {
  convertValue,
  getApiData,
  getDefaultSelectListProps,
  getSelectList,
  getTreeKeyList,
  transformValue,
} from '@/util/util';
import { Switch } from 'antd';
import useAuth from '@/hooks/useAuth';
import usePageVariable from '@/hooks/usePageVariable';
import MyPageContainer from '@/components/MyPageContainer';
import MyIconSelect from '@/components/MyIconSelect';
import MyIcon from '@/components/MyIcon';
import MyScrollTable from '@/components/MyScrollTable';
import MyForm from '@/components/MyForm';
import useDefaultColumn from '@/hooks/useDefaultColumn';

type DataType = MENU_TYPE.Info;
const initTarget = '0';
const TableList: React.FC = () => {
  const [checkTarget, setCheckTarget] = useState<string>(initTarget);
  const [expandedRowKeys, setExpandedRowKeys] = useState<Key[]>([]);
  const defaultColumn = useDefaultColumn();
  const { insertAuth, updateAuth, detailAuth, delAuth } = useAuth(MENU_CODES.MENU);
  const {
    formModel,
    setFormModel,
    formType,
    actionRef,
    formRef,
    currentRow,
    finishMsg,
    columns,
    changeForm,
    getFormTitle,
    delMsgOpen,
    setDelMsgOpen,
  } = usePageVariable<DataType>([
    defaultColumn.title,
    {
      title: '类型',
      dataIndex: 'target',
      valueType: 'select',
      hideInSearch: true,
      request: () => getSelectList(getDefaultSelectListProps('menuType')),
    },
    {
      title: '图标',
      dataIndex: 'iconName',
      hideInSearch: true,
      render: (_, record) => {
        return <MyIcon className="text-[18px]" name={record.iconName} />;
      },
    },
    {
      title: '标识',
      dataIndex: 'code',
      hideInSearch: true,
    },
    {
      title: '显示',
      dataIndex: 'isShow',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Switch
            checkedChildren="显示"
            unCheckedChildren="隐藏"
            checked={record.isShow === 1}
            disabled={record?.id === '1'}
            onChange={(checked) => {
              updateItem({
                ...record,
                isShow: !checked ? 0 : 1,
              }).then(() => {
                actionRef.current?.reload();
              });
            }}
          />
        );
      },
    },
    {
      ...defaultColumn.seq,
      sorter: false,
    },
    {
      title: '操作',
      valueType: 'option',
      render: (_, record) => [
        updateAuth &&
          getOptionBtn(AUTH_TYPE.UPDATE, () => changeForm(record, '1'), record?.id === '1'),
        detailAuth && getOptionBtn(AUTH_TYPE.DETAIL, () => changeForm(record, '2')),
        delAuth &&
          getOptionBtn(AUTH_TYPE.DELETE, () => changeForm(record, '3'), record?.id === '1'),
      ],
    },
  ]);

  const delCall = () =>
    finishMsg(async () => {
      const ret = await delItem(currentRow!.id);
      setDelMsgOpen(false);
      if (ret.success) actionRef.current?.reload();
    });

  const onFinish = async (value: DataType) => {
    if (formType === '2') {
      setFormModel(false);
      return;
    }
    await finishMsg(async () => {
      value.isShow = value.isShow ? 1 : 0;
      await (formType === '1' ? updateItem({ ...value, id: currentRow!.id }) : addItem(value));
      setFormModel(false);
      actionRef.current?.reload();
      formRef.current?.resetFields();
    });
  };

  const onOpenChange = (open: boolean) => {
    setCheckTarget(initTarget);
    setFormModel(open);
  };
  const getDetail = async () => {
    const ret = await detailItem(currentRow!.id);
    setCheckTarget(ret.target);
    return ret;
  };

  return (
    <MyPageContainer modelOk={delCall} delMsgOpen={delMsgOpen} modelCancel={setDelMsgOpen}>
      <MyScrollTable<DataType, PageParams>
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const ret = await getTreeList(params, sort, filter);
          setExpandedRowKeys([...getTreeKeyList(ret.data)]);
          return ret;
        }}
        columns={columns}
        clickAdd={changeForm}
        isAdd={insertAuth}
        x="max-content"
        pagination={false}
        expandable={{
          expandedRowKeys,
        }}
      />
      <MyForm
        formRef={formRef}
        title={getFormTitle()}
        open={formModel}
        request={currentRow?.id ? getDetail : undefined}
        onOpenChange={onOpenChange}
        onFinish={onFinish}
        readonly={formType === '2'}
        initialValues={{
          target: initTarget,
          isShow: true,
          seq: 0,
        }}
      >
        <ProFormTreeSelect
          label="上级菜单"
          name="parentId"
          fieldProps={{
            fieldNames: {
              label: 'title',
              value: 'id',
              children: 'children',
            },
          }}
          request={() =>
            getApiData(() =>
              getTreeList({
                target: '0',
              }),
            )
          }
          rules={[
            {
              required: true,
              message: '上级菜单为必填项',
            },
          ]}
        />

        <ProFormText
          label="名称"
          name="title"
          fieldProps={{
            maxLength: 30,
            showCount: true,
          }}
          rules={[
            {
              required: true,
              message: '名称为必填项',
            },
          ]}
        />
        <ProFormRadio.Group
          label="类型"
          name="target"
          fieldProps={{
            value: checkTarget,
            onChange: (e) => {
              setCheckTarget(e.target.value);
            },
          }}
          request={() => getSelectList(getDefaultSelectListProps('menuType'))}
          rules={[
            {
              required: true,
              message: '类型为必填项',
            },
          ]}
        />
        <ProFormText
          label="标识"
          name="code"
          fieldProps={{
            maxLength: 30,
            showCount: true,
          }}
          rules={[
            {
              required: true,
              message: '标识为必填项',
            },
          ]}
        />
        {checkTarget === '1' && (
          <>
            <ProFormText
              label="接口地址"
              name="interfacePath"
              rules={[
                {
                  required: true,
                  message: '接口地址为必填项',
                },
              ]}
            />
            <ProFormText
              label="路由地址"
              name="routerPath"
              rules={[
                {
                  required: true,
                  message: '路由地址为必填项',
                },
              ]}
            />
            <ProFormCheckbox.Group
              label="权限标识"
              name="actionType"
              request={() => getSelectList(getDefaultSelectListProps('actionType'))}
              convertValue={(value) => convertValue(value)}
              transform={(value) => transformValue(value)}
            />
          </>
        )}
        <MyIconSelect readonly={formType === '2'} />
        <ProFormDigit label="排序" name="seq" />
        <ProFormSwitch label="是否显示" name="isShow" />
      </MyForm>
    </MyPageContainer>
  );
};

export default TableList;
